﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace MLBService.Resources
{
    [DataContract]
    public class FranchiseItem
    {
        #region Properties

        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Designator { get; set; }
        [DataMember]
        public bool IsActive { get; set; }
        [DataMember]
        public List<UriLink> Teams = new List<UriLink>();

        #endregion

        public FranchiseItem Load(int franchiseId)
        {
            using (Model.fourseamEntities context = new Model.fourseamEntities())
            {
                var franch =
                    from f in context.Franchises
                    where f.FranchiseId == franchiseId
                    select new
                    {
                        name = f.FranchiseName,
                        id = f.FranchiseId,
                        designator = f.FranchiseDesignator,
                        isactive = f.IsActive
                    };

                var teams =
                    from t in context.FieldedTeams
                    from n in context.TeamNickNames
                    where t.FranchiseId == franchiseId
                        && n.TeamNickNameId == t.TeamNickNameId
                    orderby t.Yr
                    select new
                    {
                        id = t.FieldedTeamId,
                        yr = t.Yr,
                        nick = n.NickName
                    };

                var props = franch.FirstOrDefault();
                this.Name = props.name;
                this.Id = props.id;
                this.Designator = props.designator;
                this.IsActive = props.isactive;

                var franchiseTeams = teams.ToList();
                foreach (var itm in franchiseTeams)
                {
                    Teams.Add(new UriLink(string.Format("{0}team/{1}", Constants.baseUrl, itm.id), string.Format("{0} {1}", itm.yr, itm.nick)));
                }
            }

            return this;
        }

    }
}